package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.CoefficientMapper;
import com.iretailer.report.model.Coefficient;
import com.iretailer.report.model.CoefficientCompany;
import com.iretailer.report.model.CoefficientZone;
import com.iretailer.report.model.ZoneCoefficient;
import com.iretailer.report.util.StringUtil;
import com.iretailer.report.util.TimeUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CoefficientService extends ServiceImpl<CoefficientMapper, Coefficient> {
    @Autowired
    private CoefficientMapper coefficientMapper;
    @Autowired
    private CoefficientZoneService coefficientZoneService;

    public PageResult<CoefficientCompany> gridCoefficient(List<String> companyId, String companyName, QueryOption queryOption) {
        Page page = new Page<CoefficientCompany>(1, Long.MAX_VALUE);
        QueryWrapper<CoefficientCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", 1);
        if (companyId != null) {
            queryWrapper.in("companyId", companyId);
        }
        if (companyName != null) {
            queryWrapper.like("companyName", companyName);
        }
        queryOption.judge(page, queryWrapper);
        queryWrapper.orderByAsc("CompanyId");
        coefficientMapper.selectPageCoefficientCompanyName(page, queryWrapper);
//        coefficientMapper.selectPage(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * 根据 userId 查询出 user 下的 business
     */
   public List<Coefficient> selectByCompanyId(@Param("companyId") String companyId){
       return coefficientMapper.selectByCompanyId(companyId);
   }

    public List<Coefficient> selectByZoneIds(List<String> ZoneId) {
        return coefficientMapper.selectByZoneIds(ZoneId);
    }

    /**
     * 根据 mallId 查询出 其所有的 Coefficient
     */
    public List<Coefficient> selectByZoneId(String zoneId) {
        return coefficientMapper.selectByZoneId(zoneId);
    }

    public ZoneCoefficient filterCoefficient(String zoneId, LocalDateTime dateTime) {

        List<ZoneCoefficient> coefficientMalls = coefficientZoneService.selectMallCoefficient(new QueryWrapper<CoefficientZone>().eq("ZoneId", zoneId));
        if (coefficientMalls != null && coefficientMalls.size() > 0) {
            for (ZoneCoefficient b : coefficientMalls) {
                ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.of(b.getTimeZone()));
                String weekDay = TimeUtil.getWeekOfZonedDateTime(zonedDateTime);
                if (b.getWeekdays().contains(weekDay)) {
                    return b;
                }
            }
        }
        return new ZoneCoefficient();
    }
    public Map<String, ZoneCoefficient> filterCoefficient(String zoneId, List<String> dates) {
        List<ZoneCoefficient> zoneCoefficient = coefficientZoneService.selectMallCoefficient(new QueryWrapper<ZoneCoefficient>().eq("ZoneId", zoneId));
        Map<String, ZoneCoefficient> resultMap = new HashMap<>();
        if (zoneCoefficient != null && zoneCoefficient.size() > 0) {
            for (String date : dates) {
                for (ZoneCoefficient b : zoneCoefficient) {
                    LocalDate dateL = TimeUtil.parse_LocalDate(date);
                    if (!dateL.isBefore(b.getStartDate()) && !dateL.isAfter(b.getEndDate())) {
                        String weekDay = TimeUtil.getWeekOfLocalDate(dateL);
                        if (b.getWeekdays().contains(weekDay)) {
                            resultMap.put(date, b);
                            break;
                        }
                    }
                }
            }
        }
        return resultMap;
    }

    public ZoneCoefficient filterCoefficient(String zoneId, String date) {
        List<ZoneCoefficient> coefficients = coefficientZoneService.selectMallCoefficient(new QueryWrapper<ZoneCoefficient>().eq("MallId", zoneId));
        if (coefficients != null && coefficients.size() > 0) {
            for (ZoneCoefficient b : coefficients) {
                LocalDate dateL = TimeUtil.parse_LocalDate(date);
                if (!dateL.isBefore(b.getStartDate()) && !dateL.isAfter(b.getEndDate())) {
                    String weekDay = TimeUtil.getWeekOfLocalDate(dateL);
                    if (b.getWeekdays().contains(weekDay)) {
                        return b;
                    }
                }
            }
        }
        return new ZoneCoefficient();

    }

    /**
     * 新增   更新
     */
    @Override
    public boolean saveOrUpdate(Coefficient coefficient) {
        if (StringUtil.notEmpty(coefficient.getId())) {
            coefficientMapper.updateById(coefficient);
        } else {
            coefficientMapper.insert(coefficient);
        }
        return true;
    }

    
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean creatCoefficient(Coefficient coefficient, String oldId, String zoneId) {
        // 新建一个 Coefficient
        coefficientMapper.insert(coefficient);
        // 删除 老的关联
        deleteCoefficientZoneByCoefficientIdAndZoneId(oldId, zoneId);
        // 插入新的关联
        coefficientMapper.insertCoefficientIds(coefficient.getId(), Arrays.asList(zoneId));
        return true;
    }


    public boolean deleteCoefficientByIds(List<Long> ids) {
        if (!ids.isEmpty()) {
            coefficientMapper.deleteCoefficientByIds(ids);
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteCoefficientZoneByCoefficientIdAndZoneId(String coefficientId, String zoneId) {
        coefficientMapper.deleteCoefficientZoneByCoefficientIdAndZoneId(coefficientId, zoneId);
        return true;
    }

    /**
     * 根据主键进行删除
     */
    public boolean deleteByIds(List<String> ids) {
        List<CoefficientZone> coefficientZones = coefficientZoneService.list(new QueryWrapper<CoefficientZone>().lambda().in(CoefficientZone::getCoefficientId, ids));
        if (coefficientZones != null && coefficientZones.size() > 0) {
            return false;
        } else {
            coefficientMapper.deleteBatchIds(ids);
            return true;
        }
    }

    /**
     * 根据 主键 更新 mallIds 的关联
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean saveCoefficientZones(String id, List<String> zoneIds) {
        if (StringUtil.notEmpty(id) && zoneIds != null) {
            coefficientMapper.deleteCoefficientZonesByCoefficientId(id);
            if (zoneIds.size() > 0) {
                coefficientMapper.insertCoefficientIds(id, zoneIds);
            }
            return true;
        } else {
            return false;
        }
    }


    public boolean insertCoefficientMalls(String id, List<String> zoneIds) {
        return coefficientMapper.insertCoefficientIds(id, zoneIds) > 0;
    }

    public List<String> findZoneIdsByCoefficientId(String coefficientId) {
       return coefficientMapper.findZoneIdsByCoefficientId(coefficientId);
    }
}
